package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserCenterMapper;
import com.heima.user.service.ApUserAutoAuditService;
import com.heima.user.service.ApUserCenterService;
import com.heima.user.service.ApUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * @author:Dikk
 * @create: 2023-08-04 16:57
 * @Description: ApUserCenterServiceImpl
 */
@Service
@Slf4j
public class ApUserCenterServiceImpl extends ServiceImpl<ApUserCenterMapper, ApUserRealname> implements ApUserCenterService {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApUserAutoAuditService apUserAutoAuditService;

    @Autowired
    private ApUserService apUserService;

    @Autowired
    private IWemediaClient wemediaClient;

    /**
     * 上传照片
     *
     * @param fontImage 身份证正面照片
     * @param backImage 身份证背面照片
     * @param holdImage 手持照片
     * @param liveImage 活体照片
     * @param userId    用户id
     * @param name      用户名
     * @param idno      身份证号
     * @return
     */
    @Override
    public ResponseResult uploadCertificate(MultipartFile fontImage, MultipartFile backImage, MultipartFile holdImage, MultipartFile liveImage, Integer userId, String name, String idno) {

        //获取照片路径
        String fontImagePath = getFileUploadPath(fontImage);
        String backImagePath = getFileUploadPath(backImage);
        String holdImagePath = getFileUploadPath(holdImage);
        String liveImagePath = getFileUploadPath(liveImage);

        //参数校验
        checkParam(fontImagePath);
        checkParam(backImagePath);
        checkParam(holdImagePath);
        checkParam(liveImagePath);

        //封装数据
        ApUserRealname apUserRealname = ApUserRealname.builder()
                .backImage(backImagePath)
                .fontImage(fontImagePath)
                .holdImage(holdImagePath)
                .liveImage(liveImagePath)
                .name(name).userId(userId)
                .updatedTime(new Date())
                .createdTime(new Date())
                .idno(idno).build();

        //自动审核
        Map<String, String> map = apUserAutoAuditService.idCard(fontImagePath);

        //判断返回值是否为1 为1表示通过 剩下交由人工审核
        Integer numberType = Integer.valueOf(map.get("idcard_number_type"));
        if (numberType == 1) {
            //审核通过 封装剩余属性
            apUserRealname.setIdno(map.get("cardNumber"));
            apUserRealname.setSubmitedTime(new Date());
            apUserRealname.setStatus(ApUserRealname.Status.PASS.getCode());
            //将apUser中的信息认证通过
            ApUser apUser = apUserService.getById(userId);
            if (Objects.isNull(apUser)) {
                apUser = new ApUser();
            }
            if ("男".equals(map.get("sex"))) {
                apUser.setSex((short) 0);
            } else if ("女".equals(map.get("sex"))) {
                apUser.setSex((short) 1);
            } else {
                apUser.setSex((short) 2);
            }
            apUser.setCertification((short) 1);
            apUser.setIdentityAuthentication(true);
            apUser.setFlag((short) 1);

            apUserService.updateById(apUser);
            //将wmUser中的属性更新
            WmUser wmUser = new WmUser();
            BeanUtils.copyProperties(apUser, wmUser);
            wmUser.setApUserId(apUser.getId());
            wmUser.setId(null);
            wmUser.setStatus((int) ApUserRealname.Status.PASS.getCode());
            wmUser.setCreatedTime(new Date());
            wmUser.setLocation(map.get("address"));
            wmUser.setType(0);
            //调用微服务,将数据存入到wmUser中
            wemediaClient.setWmUser(wmUser);
        } else {
            //审核失败,交由人工审核
            apUserRealname.setStatus(ApUserRealname.Status.STAY.getCode());
        }
        save(apUserRealname);

        return ResponseResult.okResult(apUserRealname);
    }

    /**
     * 上传文件获取路径
     *
     * @param file
     * @return
     */
    public String getFileUploadPath(MultipartFile file) {

        try {
            String lastName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

            String firstName = UUID.randomUUID().toString();

            //上传图片
            String filePath = fileStorageService.uploadImgFile("", firstName + lastName, file.getInputStream());

            return filePath;
        } catch (IOException e) {
            log.info("文件上传失败,失败原因:{}", e);
            return null;
        }
    }

    public ResponseResult checkParam(String path) {
        if (StringUtils.isBlank(path)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        return null;
    }
}
